﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8_MyAtoi
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "123";
            int result = MyAtoi(str);
            Console.WriteLine(result);
            Console.ReadLine();
        }

        private static int MyAtoi(string str)
        {
            if (str == null || str.Length == 0)
                return 0;//
            str = str.Trim();
            char firstChar = str[0];
            int sign = 1, start = 0, len = str.Length;
            long sum = 0;
            if (firstChar == '+')
            {
                sign = 1;
            }
            else if (firstChar == '-')
            {
                sign = -1;
            }
            start++;

            for (int i = start; i < len; i++)
            {
                int temp = 0;
                if (!int.TryParse(str[i].ToString(), out temp))
                    return (int)sum * sign;
                sum = sum * 10 + str[i] - '0';
                if (sign == 1 && sum > int.MaxValue)
                    return int.MaxValue;
                if (sign == -1 && (-1) * sum < int.MinValue)
                    return int.MinValue;
            }

            return (int)sum * sign;
        }

    }
}
